<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>用户显示问题调试</title>
    <style>
      body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        margin: 0;
        padding: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
      }
      .container {
        max-width: 1200px;
        margin: 0 auto;
        background: white;
        border-radius: 16px;
        padding: 30px;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
      }
      .header {
        text-align: center;
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 2px solid #f0f0f0;
      }
      .header h1 {
        color: #333;
        margin: 0;
        font-size: 28px;
      }
      .header p {
        color: #666;
        margin: 10px 0 0 0;
      }
      .section {
        margin-bottom: 30px;
        padding: 20px;
        border: 1px solid #e0e0e0;
        border-radius: 12px;
        background: #fafafa;
      }
      .section h3 {
        margin: 0 0 15px 0;
        color: #444;
        font-size: 18px;
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .icon {
        width: 20px;
        height: 20px;
      }
      .test-controls {
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
      }
      .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
      }
      .btn-primary {
        background: #007bff;
        color: white;
      }
      .btn-success {
        background: #28a745;
        color: white;
      }
      .btn-danger {
        background: #dc3545;
        color: white;
      }
      .btn-warning {
        background: #ffc107;
        color: black;
      }
      .btn:hover {
        transform: translateY(-2px);
      }
      .status-display {
        background: white;
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #007bff;
        margin-top: 15px;
      }
      .user-preview {
        display: flex;
        align-items: center;
        gap: 15px;
        padding: 15px;
        background: white;
        border-radius: 8px;
        margin-top: 15px;
        border: 1px solid #ddd;
      }
      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: #007bff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        font-weight: bold;
      }
      .user-info h4 {
        margin: 0 0 5px 0;
        color: #333;
      }
      .user-info p {
        margin: 0;
        color: #666;
        font-size: 14px;
      }
      .log {
        background: #2d3748;
        color: #e2e8f0;
        padding: 15px;
        border-radius: 8px;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        max-height: 200px;
        overflow-y: auto;
        margin-top: 15px;
      }
      .log-entry {
        margin-bottom: 5px;
        padding: 2px 0;
      }
      .log-error {
        color: #fc8181;
      }
      .log-success {
        color: #68d391;
      }
      .log-warning {
        color: #f6e05e;
      }
      .log-info {
        color: #63b3ed;
      }
      .grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
      }
      .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: bold;
        text-transform: uppercase;
      }
      .status-online {
        background: #d4edda;
        color: #155724;
      }
      .status-offline {
        background: #f8d7da;
        color: #721c24;
      }
      .status-loading {
        background: #fff3cd;
        color: #856404;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h1>🔍 用户显示问题调试工具</h1>
        <p>检测和修复用户信息显示、Token存储、API响应等问题</p>
      </div>

      <div class="grid">
        <!-- API连接测试 -->
        <div class="section">
          <h3>
            🌐 API连接测试
            <span id="api-status" class="status-badge status-offline"
              >离线</span
            >
          </h3>
          <div class="test-controls">
            <button class="btn btn-primary" onclick="testAPIConnection()">
              测试连接
            </button>
            <button class="btn btn-warning" onclick="testAuthAPI()">
              测试认证API
            </button>
          </div>
          <div
            id="api-status-display"
            class="status-display"
            style="display: none"
          >
            <strong>API状态:</strong> <span id="api-result">检测中...</span>
          </div>
        </div>

        <!-- Token存储测试 -->
        <div class="section">
          <h3>🔑 Token存储测试</h3>
          <div class="test-controls">
            <button class="btn btn-success" onclick="testTokenStorage()">
              测试存储
            </button>
            <button class="btn btn-warning" onclick="simulateLogin()">
              模拟登录
            </button>
            <button class="btn btn-danger" onclick="clearAllStorage()">
              清除存储
            </button>
          </div>
          <div id="token-status" class="status-display">
            <div>
              <strong>localStorage Token:</strong>
              <span id="local-token">无</span>
            </div>
            <div>
              <strong>sessionStorage Token:</strong>
              <span id="session-token">无</span>
            </div>
            <div>
              <strong>记住登录状态:</strong>
              <span id="remember-status">否</span>
            </div>
            <div>
              <strong>记住的邮箱:</strong> <span id="remembered-email">无</span>
            </div>
          </div>
        </div>

        <!-- 用户数据测试 -->
        <div class="section">
          <h3>👤 用户数据测试</h3>
          <div class="test-controls">
            <button class="btn btn-primary" onclick="testUserAPI()">
              获取用户信息
            </button>
            <button class="btn btn-success" onclick="testDataStructure()">
              检查数据结构
            </button>
          </div>
          <div id="user-preview" class="user-preview" style="display: none">
            <div id="user-avatar" class="avatar">?</div>
            <div class="user-info">
              <h4 id="user-name">用户名</h4>
              <p id="user-details">用户详情</p>
            </div>
          </div>
        </div>

        <!-- 前端组件测试 -->
        <div class="section">
          <h3>⚛️ 前端组件测试</h3>
          <div class="test-controls">
            <button class="btn btn-primary" onclick="testHeaderDisplay()">
              测试头部显示
            </button>
            <button class="btn btn-success" onclick="testReactivity()">
              测试响应性
            </button>
          </div>
          <div id="component-status" class="status-display">
            <div>
              <strong>组件状态:</strong>
              <span id="component-result">未测试</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时日志 -->
      <div class="section">
        <h3>📋 实时调试日志</h3>
        <div class="test-controls">
          <button class="btn btn-warning" onclick="clearLog()">清除日志</button>
          <button class="btn btn-primary" onclick="runFullDiagnostic()">
            完整诊断
          </button>
        </div>
        <div id="debug-log" class="log"></div>
      </div>
    </div>

    <script>
      // 模拟LocalStorage工具类
      class TestLocalStorage {
        static REMEMBERED_EMAIL_KEY = 'novel_app_remembered_email'
        static REMEMBER_LOGIN_KEY = 'novel_app_remember_login'
        static TOKEN_KEY = 'novel_app_token'

        static setRememberedEmail(email) {
          localStorage.setItem(this.REMEMBERED_EMAIL_KEY, email)
        }

        static getRememberedEmail() {
          return localStorage.getItem(this.REMEMBERED_EMAIL_KEY)
        }

        static clearRememberedEmail() {
          localStorage.removeItem(this.REMEMBERED_EMAIL_KEY)
        }

        static setRememberLogin(remember) {
          localStorage.setItem(this.REMEMBER_LOGIN_KEY, remember.toString())
        }

        static getRememberLogin() {
          const remember = localStorage.getItem(this.REMEMBER_LOGIN_KEY)
          return remember === 'true'
        }

        static setTokenWithRemember(token, remember) {
          if (remember) {
            localStorage.setItem(this.TOKEN_KEY, token)
            sessionStorage.removeItem(this.TOKEN_KEY)
            this.setRememberLogin(true)
          } else {
            sessionStorage.setItem(this.TOKEN_KEY, token)
            localStorage.removeItem(this.TOKEN_KEY)
            this.setRememberLogin(false)
          }
        }

        static getTokenFromStorage() {
          let token = localStorage.getItem(this.TOKEN_KEY)
          if (token) return token

          token = sessionStorage.getItem(this.TOKEN_KEY)
          return token
        }

        static clearAllTokens() {
          localStorage.removeItem(this.TOKEN_KEY)
          sessionStorage.removeItem(this.TOKEN_KEY)
        }
      }

      // 日志系统
      function addLog(message, type = 'info') {
        const log = document.getElementById('debug-log')
        const timestamp = new Date().toLocaleTimeString()
        const entry = document.createElement('div')
        entry.className = `log-entry log-${type}`
        entry.textContent = `[${timestamp}] ${message}`
        log.appendChild(entry)
        log.scrollTop = log.scrollHeight
      }

      // API连接测试
      async function testAPIConnection() {
        addLog('开始测试API连接...', 'info')
        const status = document.getElementById('api-status')
        const display = document.getElementById('api-status-display')
        const result = document.getElementById('api-result')

        try {
          const response = await fetch('http://localhost:3000/api/auth/me', {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          })

          if (response.status === 401) {
            status.className = 'status-badge status-loading'
            status.textContent = '需要认证'
            result.textContent = 'API服务正常，但需要认证'
            addLog('API服务正常运行，返回401（需要认证）', 'success')
          } else if (response.ok) {
            status.className = 'status-badge status-online'
            status.textContent = '在线'
            result.textContent = 'API服务正常'
            addLog('API服务正常运行', 'success')
          } else {
            throw new Error(`HTTP ${response.status}`)
          }

          display.style.display = 'block'
        } catch (error) {
          status.className = 'status-badge status-offline'
          status.textContent = '离线'
          result.textContent = `连接失败: ${error.message}`
          addLog(`API连接失败: ${error.message}`, 'error')
          display.style.display = 'block'
        }
      }

      // Token存储测试
      function testTokenStorage() {
        addLog('测试Token存储功能...', 'info')
        updateTokenDisplay()
        addLog('Token存储状态已更新', 'success')
      }

      function updateTokenDisplay() {
        document.getElementById('local-token').textContent =
          localStorage.getItem('novel_app_token') || '无'
        document.getElementById('session-token').textContent =
          sessionStorage.getItem('novel_app_token') || '无'
        document.getElementById('remember-status').textContent =
          TestLocalStorage.getRememberLogin() ? '是' : '否'
        document.getElementById('remembered-email').textContent =
          TestLocalStorage.getRememberedEmail() || '无'
      }

      // 模拟登录
      function simulateLogin() {
        const mockToken = 'test-token-' + Date.now()
        const remember = Math.random() > 0.5

        TestLocalStorage.setTokenWithRemember(mockToken, remember)
        if (remember) {
          TestLocalStorage.setRememberedEmail('test@example.com')
        }

        addLog(`模拟登录成功，记住登录: ${remember}`, 'success')
        updateTokenDisplay()
      }

      // 清除存储
      function clearAllStorage() {
        TestLocalStorage.clearAllTokens()
        TestLocalStorage.clearRememberedEmail()
        TestLocalStorage.clearRememberLogin()
        addLog('已清除所有存储数据', 'warning')
        updateTokenDisplay()
      }

      // 测试用户API
      async function testUserAPI() {
        addLog('测试用户信息API...', 'info')
        const token = TestLocalStorage.getTokenFromStorage()

        if (!token) {
          addLog('没有Token，无法测试用户API', 'warning')
          return
        }

        try {
          const response = await fetch('http://localhost:3000/api/auth/me', {
            method: 'GET',
            headers: {
              Authorization: `Bearer ${token}`,
              'Content-Type': 'application/json',
            },
          })

          const data = await response.json()
          addLog(`API响应: ${JSON.stringify(data)}`, 'info')

          if (data.success && data.data && data.data.user) {
            displayUserPreview(data.data.user)
            addLog('用户信息获取成功', 'success')
          } else {
            addLog('用户信息格式异常', 'error')
          }
        } catch (error) {
          addLog(`用户API测试失败: ${error.message}`, 'error')
        }
      }

      // 显示用户预览
      function displayUserPreview(user) {
        const preview = document.getElementById('user-preview')
        const avatar = document.getElementById('user-avatar')
        const name = document.getElementById('user-name')
        const details = document.getElementById('user-details')

        const displayName = user.nickname || user.username || '未知用户'
        avatar.textContent = displayName.charAt(0).toUpperCase()
        name.textContent = displayName
        details.textContent = `ID: ${user.id}, 邮箱: ${user.email}`

        preview.style.display = 'flex'
      }

      // 测试数据结构
      function testDataStructure() {
        addLog('检查前端期望的数据结构...', 'info')

        const expectedStructure = {
          success: true,
          user: {
            id: 'number|string',
            email: 'string',
            nickname: 'string?',
            username: 'string?',
            avatar: 'string?',
            avatar_url: 'string?',
          },
        }

        addLog(
          `前端期望结构: ${JSON.stringify(expectedStructure, null, 2)}`,
          'info'
        )
        addLog('请检查后端返回是否匹配此结构', 'warning')
      }

      // 测试认证API
      async function testAuthAPI() {
        addLog('测试认证相关API端点...', 'info')

        const endpoints = [
          '/api/auth/me',
          '/api/auth/login',
          '/api/auth/logout',
        ]

        for (const endpoint of endpoints) {
          try {
            const response = await fetch(`http://localhost:3000${endpoint}`, {
              method: 'GET',
            })

            addLog(
              `${endpoint}: ${response.status} ${response.statusText}`,
              response.status < 500 ? 'success' : 'error'
            )
          } catch (error) {
            addLog(`${endpoint}: 连接失败`, 'error')
          }
        }
      }

      // 完整诊断
      async function runFullDiagnostic() {
        addLog('🚀 开始完整系统诊断...', 'info')

        await testAPIConnection()
        await new Promise((resolve) => setTimeout(resolve, 1000))

        testTokenStorage()
        await new Promise((resolve) => setTimeout(resolve, 500))

        await testAuthAPI()
        await new Promise((resolve) => setTimeout(resolve, 500))

        testDataStructure()

        addLog('✅ 完整诊断完成', 'success')
      }

      // 清除日志
      function clearLog() {
        document.getElementById('debug-log').innerHTML = ''
      }

      // 页面加载时初始化
      window.addEventListener('load', function () {
        addLog('🔧 调试工具初始化完成', 'success')
        updateTokenDisplay()
      })
    </script>
  </body>
</html>
